package com.dwd.basic.service.impl;

import com.dwd.basic.constant.VerificationConstant;
import com.dwd.basic.exception.CustomException;
import com.dwd.basic.service.IVerificationService;
import com.dwd.basic.utils.SendMsgUtils;
import com.dwd.basic.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/17 22:09
 * @Version 1.0
 */
@Service
public class VerificationServiceImpl implements IVerificationService {

    /**
     * 注入redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @throws CustomException
     */
    @Override
    public void sendMobileCode(String phone) throws CustomException {
        //随机产生四个字符
        String randomString = StrUtils.getComplexRandomString(4);
        //获取验证码
        String old = (String) redisTemplate.opsForValue().get(phone + ":" + VerificationConstant.USER_REG);
        //如果拿得到，说明还没到五分钟
        if (!StringUtils.isEmpty(old)) {
            Long befor = Long.valueOf(old.split(":")[1]);
            if (System.currentTimeMillis() - befor <= 60 * 1000) {
                //没到一分钟
                throw new CustomException("没到一分钟");
            }
            //过了一分钟没到五分钟,还是发送之前的验证码
            randomString = old.split(":")[0];
        }

        //存入redis 五分钟过期
        redisTemplate.opsForValue().set(phone + ":" + VerificationConstant.USER_REG,
                randomString + ":" + System.currentTimeMillis(), 5, TimeUnit.MILLISECONDS);
        //发送验证码
        //发送验证码
        String text = "汶狄告诉你，你的验证码为  " + randomString + "  请在五分钟之内完成注册";
        SendMsgUtils.send(phone, text);
    }
}
